/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mygameframework.states;

//import common.messaging.Telegram;

/**
 *
 * @author bill
 */
public class StateMachine<T> {

    private IState<T> globalState;
    private IState<T> previousState;
    private IState<T> currentState;
    private T owner;

    public StateMachine(T owner) {
        this.owner = owner;
        this.globalState = null;
        this.previousState = null;
        this.currentState = null;
    }

    /**
     * update负责调用 角色持有的 状态对象的execute方法
     */
    public void update(long elapsedTime) {
        if (globalState != null) {
            globalState.execute(owner,elapsedTime);
        }
        if (currentState != null) {
            currentState.execute(owner,elapsedTime);
        }
    }

    public void changeState(IState<T> newState) {
        assert (newState != null);
        this.previousState=this.currentState;
        //调用当前状态的exit方法
        if(currentState!=null)
            this.currentState.exit(owner);
        this.currentState=newState;
        //调用新状态的enter方法
        this.currentState.enter(owner);

    }
    /**
     * 恢复前一个状态
     */
    public void revertToPreviousState() {
        changeState(previousState);
    }

    public IState getCurrentState() {
        return currentState;
    }

    public void setCurrentState(IState<T> currentState) {
        this.currentState = currentState;
    }

    public IState<T> getGlobalState() {
        return globalState;
    }

    public void setGlobalState(IState<T> globalState) {
        this.globalState = globalState;
    }

    public IState<T> getPreviousState() {
        return previousState;
    }

    public void setPreviousState(IState<T> previousState) {
        this.previousState = previousState;
    }
//    public boolean handleMessage(Telegram msg){
//        if(currentState!=null && currentState.onMessage(owner, msg)){
//            return true;
//        }
//        if(globalState!=null&& globalState.onMessage(owner, msg)){
//            return true;
//        }
//        return false;
//    }
}
